package driver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import nonogram.NonogramSolver;

public class Driver {

	public static void main(String[] args) {
		if (args.length < 1) {
			argsHelp();
			return;
		}
		
		String fileName = args[0];
		String htmlSolvedFileName = fileName + "-solved.html";

		FileInputStream fstream;
		try {
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			URL url = classLoader.getResource("");
			String fileLocation = url.getFile().replace("%20", " ").replace("bin/", "puzzles/");
			
			fstream = new FileInputStream(fileLocation + fileName);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			
			try {
				String rows = br.readLine();
				String columns = br.readLine();
				
				br.close();
				in.close();
				fstream.close();
				
				NonogramSolver solver = new NonogramSolver(rows, columns);
				solver.solve();
				
				saveHtml(fileLocation + htmlSolvedFileName, solver.toHtml());
				
				if (solver.isSolved()) {
					System.out.println("Done solving " + fileName + " in " + solver.getSeconds() + " seconds.");
				}
				else {
					System.out.println("Could not solve " + fileName + " in " + solver.getSeconds() + " seconds.");
				}
				
			} catch (IOException e) {
//				e.printStackTrace();
				fileContentHelp();
			}
			
		} catch (FileNotFoundException e) {
//			e.printStackTrace();
			argsHelp();
		}

	}

	public static void argsHelp() {
		System.out.println("Need arg with valid file name");
	}
	
	public static void fileContentHelp() {
		System.out.println("Need file with a line for rows and columns");
	}
	
	public static void saveHtml(String fullFileLocation, String html) throws IOException {
		File f = new File(fullFileLocation);
		boolean readyToCreate = true;
		
		if (f.isFile()) {
			readyToCreate = f.delete();
		}
		
		if (!readyToCreate) {
			System.out.println("Could not create html file");
			return;
		}
		
		FileOutputStream fstream = new FileOutputStream(fullFileLocation);
		DataOutputStream out = new DataOutputStream(fstream);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
		
		bw.write(html);
		
		bw.close();
		out.close();
		fstream.close();
	}
}
